using System.ComponentModel;
using CSW.Framework.Common.Binding;
using CSW.Framework.Common.Binding.Events;
using CSW.Framework.UI.Binding;
using DevExpress.XtraEditors;

namespace CSW.Framework.UI.DevEx.Binding
{
    /// <summary>
    /// A wrapper class for binding <see cref="ComboBoxEdit"/> objects with <see cref="Binder"/>.
    /// </summary>
    public class BindableComboBoxEditChangingList<T> : BindableComboBoxEdit
    {
        private readonly UnboundProperty<BindingList<T>> m_ValueListProperty;

        /// <summary>
        /// Initializes a new instance of the <see cref="BindableComboBoxEditChangingList&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="comboBoxEdit">The <see cref="ComboBoxEdit"/> control to wrap.</param>
        /// <param name="valueListProperty">The value list <see cref="ComplexProperty" />.</param>
        /// <param name="addClearButton">if set to <c>true</c>, add a clear button.</param>
        public BindableComboBoxEditChangingList(ComboBoxEdit comboBoxEdit, UnboundProperty<BindingList<T>> valueListProperty, bool addClearButton)
            : base(comboBoxEdit, valueListProperty.Value ?? new BindingList<T>(), addClearButton)
        {
            m_ValueListProperty = valueListProperty;
            m_ValueListProperty.PropertyChanged += m_ValueListProperty_PropertyChanged;
        }

        private void m_ValueListProperty_PropertyChanged(object sender, TypedPropertyChangedEventArgs<BindingList<T>> e)
        {
            CheckDisposed();

            ValueList = m_ValueListProperty.Value;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public override void Dispose()
        {
            m_ValueListProperty.PropertyChanged -= m_ValueListProperty_PropertyChanged;

            base.Dispose();
        }
    }
}